﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using log4net;
using log4net.Repository.Hierarchy;

namespace IBS.Bll
{

    public class NotificationService
    {
        private static MailAddress fromAddress;
        private static string fromPassword;
        private static SmtpClient smtp = new SmtpClient(@"smtp.gmail.com", 587);

        private static readonly ILog log = LogManager.GetLogger(typeof (NotificationService));

        static NotificationService()
        {
            fromPassword = Configuration.MailPassword;
            fromAddress = new MailAddress(Configuration.MailFromAddress, Configuration.MailFromUser);
         
            smtp.EnableSsl = true;
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new NetworkCredential(fromAddress.Address, fromPassword);
        }

        public static void SendNotificationEmail(string mail, string userName,
             string subject, string body)
        {
            try
            {
                var toAddress = new MailAddress(mail, userName);

                using (var message = new MailMessage(fromAddress, toAddress)
                                         {
                                             Subject = subject,
                                             Body = body
                                         })
                {
                    smtp.Send(message);
                }

            }
            catch(Exception exception)
            {
                log.ErrorFormat("Message to user = {0} with email =  {1} hasn't be sending.\r exception = {2}", userName, mail, exception.Message);
            }
        }
    }
}
